<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8" />
		<title></title>
		<style>
			.box {
				margin: auto;
				width: 500px;
				height: 500px;
				background-color: coral;
			}
			
			.on {
				background-color: black;
			}
			
			.wrap {
				height: 200px;
			}
			
			button {
				margin: 0 auto;
			}
			
			#but {
				margin: 0 auto;
				width: 1200px;
			}
		</style>
	</head>

	<body>
		<div id="but">
			<label>仅限增加单个类名:</label>
			<input type="text" class="input-one" />
			<button type="button" onclick="pushClass()">增加类名</button>
			<label>仅限删除单个类名:</label>
			<input type="text" class="input-two" />
			<button type="button" onclick="pullClass()">删除类名</button> 当前类名: <input type="text" class="input-three" />
		</div>
		<div id="box" class="box car on on  car"></div>
	</body>
	<script type="text/javascript">
		var input_one = document.getElementsByClassName("input-one")[0];
		var input_two = document.getElementsByClassName("input-two")[0];
		var input_three = document.getElementsByClassName("input-three")[0];
		var ele = document.getElementById('box');
		putClass();
		//增加按鈕
		function pushClass() {
			var getInputClass = input_one.value;
			if(getInputClass) {
				getInputClass = getInputClass.trim();
				addClass(ele, getInputClass);
				putClass();
			}
		}
		//刪除按鈕
		function pullClass() {
			var getInputClass = input_two.value;
			if(getInputClass) {
				getInputClass = getInputClass.trim();
				removeClass(ele, getInputClass);
				putClass();
			}

		}
		//更新文本框
		function putClass() {
			input_three.value = ele.className;
		}
		//---------------------------------------------------------------------------------------------------		
		/**
		 * 1.获取元素
		 * 2.传参
		 * 
		 */
		
		//		addClass(ele, "on");
		//增加类名
		function addClass(ele, ref) {
			if(typeof(ele) !== "object") {
				return console.log(ele + " is not Object");
			}
			if(typeof(ref) !== "string") {
				return console.log(ref + " is not String");
			}
			//清除空值
			var str2 = ele.className.split(' ').filter(function(item) {
				return item === "" ? false : true;
			});
			str2.push(ref);
			//去重
			var str3 = str2.filter(function(item, index, self) {
				return self.indexOf(item) === index;
			});
			ele.className = str3.join(" ");
		}
		//删除类名
		function removeClass(ele, ref) {
			if(typeof(ele) !== "object") {
				return console.log(ele + " is not Object");
			}
			if(typeof(ref) !== "string") {
				return console.log(ref + " is not String");
			}
			//清除空值
			var str2 = ele.className.split(' ').filter(function(item) {
				return item === "" ? false : true;
			});
			//去重
			var str3 = str2.filter(function(item, index, self) {
				return self.indexOf(item) === index;
			});
			//找下标
			var myindex = str3.indexOf(ref);
			var str4 = str3.filter(function(item, index, self) {
				return myindex === index ? false : true;
			});
			ele.className = str4.join(" ");
		}
	</script>

</html>